package com.k.camera2

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.YuvImage
import android.hardware.Camera
import android.os.Environment
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object PreviewCameraUtils {

    fun cameraDataToBitmap(data: ByteArray, camera: Camera): Bitmap {
        val parameters = camera.parameters
        val width = parameters.previewSize.width
        val height = parameters.previewSize.height
        val format = parameters.previewFormat
        return yuvToBitmap(data, format, width, height)
    }

    /**
     * 将摄像头数据转换为Bitmap
     *
     * @param data
     * @param format
     * @param width
     * @param height
     * @return
     */
    fun yuvToBitmap(data: ByteArray, format: Int, width: Int, height: Int): Bitmap {
        val out = ByteArrayOutputStream()
        val yuvImage = YuvImage(data, format, width, height, null)
        yuvImage.compressToJpeg(Rect(0, 0, width, height), 100, out)
        val imageBytes = out.toByteArray()
        return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
    }

    /**
     * 对Bitmap进行旋转和翻转
     *
     * @param bitmap
     * @param rotate        旋转的角度
     * @param leftRightTurn 是否左右翻转
     * @param upDownTurn    是否上下翻转
     * @return
     */
    fun bitmapXform(
        bitmap: Bitmap,
        rotate: Int,
        leftRightTurn: Boolean,
        upDownTurn: Boolean
    ): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val matrix = Matrix()
        if (leftRightTurn) {
            matrix.preScale(-1f, 1f)
        }
        if (upDownTurn) {
            matrix.preScale(1f, -1f)
        }
        if (rotate > 0) {
            matrix.postRotate(rotate.toFloat())
        }
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
    }

    /**
     * 将Bitmap保存为jpg文件
     *
     * @param bitmap
     * @param filePath 绝对路径
     */
    fun saveBitmapToFile(bitmap: Bitmap, filePath: String) {
        val file = File(filePath)
        try {
            // 创建文件输出流
            val outputStream = FileOutputStream(file)
            // 将bitmap写入输出流中
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            // 刷新缓冲区
            outputStream.flush()
            // 关闭输出流
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 获取SDCard根路径
     *
     * @return
     */
    fun getSDCardPath(): String {
        return "" + Environment.getExternalStorageDirectory()
    }
}
